starter.controller('surveyController', function($rootScope,$state,$ionicPopup,$timeout,$scope,Page, $compile, $window, localStore,$location,$ionicHistory, $filter, $ionicFilterBar, $ionicPopover, $document) {
	$scope.routeStat = {};
	// $scope.routestat.startStopName = '11111';
	// $scope.routestat.endStopName = '2222222';
	$scope.busStops = [];  //数据源取出的站点信息
	$scope.center = {};    //当前中心
	$scope.nearByNum = 20; //显示附件站点数
	$scope.displayedMarkers = [];  //已经显示的marker
	$scope.selectedMarker = {}; //当前选中的marker
	// $scope.startMarker = {};
	// $scope.endMarker = {};
	$scope.selectedPolyline = {};
	$scope.searchFlag = false;  //只有通过搜索框的定位，才触发moveend事件
	$scope.routeStat.isWorkingDepart = false;
	$scope.routeStat.isHolidayDepart = false;
	$scope.routeStat.departType = '1';
	$scope.placeSearch = {};
	//$scope.searchName = {};
	$scope.lastSearchName = {};
	$scope.isSearchBar = false;

	$scope.screenHeight = $window.screen.height;

	//地图初始化
	$scope.init = function (id) {

		var map = new AMap.Map(id, {
			resizeEnable : true,
			zoom : 12,
			zooms : [4, 18]
		});

		//map.setMap.setMapStyle('amap://styles/light');

		//加载工具条
		map.plugin(['AMap.ToolBar'], function() {
			var toolBar = new AMap.ToolBar();
			map.addControl(toolBar);
		});

		//加载鹰眼
		/*map.plugin(["AMap.OverView"], function() {
		 var view = new AMap.OverView();
		 map.openOverView = function() {
		 view.open();
		 }
		 map.addControl(view);
		 });*/

		/*map.plugin(["AMap.Geocoder"], function() {
		 var geocoder = new AMap.Geocoder({
		 radius : 1000,
		 extensions : "all"
		 });
		 map.geoQuery = function(points, callback, errorback, parms) {
		 geocoder.getAddress(points, function(status, geoResult) {
		 if (status == 'complete' && geoResult.info === 'OK') {
		 if (callback) {
		 callback(status, geoResult, parms);
		 }
		 } else {
		 if (errorback) {
		 errorback(parms);
		 }
		 }
		 });
		 }
		 });*/

		//加载定位插件
		map.plugin('AMap.Geolocation', function () {
			geolocation = new AMap.Geolocation({
				enableHighAccuracy: true, //是否使用高精度定位，默认:true
				timeout: 10000,           //超过10秒后停止定位，默认：无穷大
				maximumAge: 0,            //定位结果缓存0毫秒，默认：0
				convert: true,            //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
				showButton: false,        //显示定位按钮，默认：true
				showMarker: false,        //定位成功后在定位到的位置显示点标记，默认：true
				showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
				zoomToAccuracy:false      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
			});

			map.addControl(geolocation);

			//geolocation.getCurrentPosition(); //精准定位
			//geolocation.getCityInfo();        //定位到城市

			AMap.event.addListener(geolocation, 'complete', function (_point) {
				Page.notice('定位成功：经度' + _point.position.getLng() + '; 维度：' + _point.position.getLat());
			});
			AMap.event.addListener(geolocation, 'error', function (_point) {
				Page.notice('定位失败');
			});
		});

		//初始中心点
		$scope.center = map.getCenter();

		//加载搜索插件
		AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],function(){
			var autoOptions = {
				city: "武汉",
				input: "keyword"//使用联想输入的input的id
			};
			autocomplete= new AMap.Autocomplete(autoOptions);
			$scope.placeSearch = new AMap.PlaceSearch({
				city:'武汉',
				map:map
			})
			AMap.event.addListener(autocomplete, "select", function(e){
				/*$scope.searchFlag = true;
				 placeSearch.search(e.poi.name);
				 $scope.isSearchBar = false;*/
			});
		});

		return map;

	}

	$scope.map = $scope.init('map');


	// 高度自适应
	$scope.mapHeight = $document.height() - (
			angular.element(document.querySelector('ion-header-bar')).outerHeight()
			+ angular.element(document.querySelector('#dd')).outerHeight()
			+ angular.element(document.querySelector('#dt')).outerHeight()
			+ angular.element(document.querySelector('#confirmButton')).outerHeight()
		);
	angular.element(document.querySelector('#mapFrame')).css('height',$scope.mapHeight + 'px');
	angular.element(document.querySelector('#mapFrame')).css('margin-top',angular.element(document.querySelector('ion-header-bar')).outerHeight() + 'px');
	/*$scope.mapStyle = {
	 "height" : $scope.mapHeight
	 }*/

	//显示站点
	Page.ajaxPost('routeStat/stops.do', {}, function(resp) {
		//摘录所有站点信息
		$(resp.data).each(function(i, _busStop) {
			var busStop = {'stopId':_busStop.stopId, 'stopName': _busStop.stopName, 'lng': _busStop.lng, 'lat': _busStop.lat};
			$scope.busStops.push(busStop);
		});

		//计算所有站点与当前中心点的距离
		$scope.calcDistance();

		//计算经纬度范围
		//$scope.calcRange();

		//显示距离最近的站点
		$scope.showStops($scope.nearByNum);


	});

	$scope.calcDistance = function () {
		//Page.notice($scope.center.getLng());

		$($scope.busStops).each(function (i, _busStop) {
			$scope.busStops[i].distance = $scope.center.distance([_busStop.lng, _busStop.lat]);
		});

		//排序
		$scope.busStops.sort(function (a, b) {
			return (a.distance < b.distance) ? -1 : 1
		})

	}

	$scope.calcRange = function () {

		$scope.center.lng = $scope.center.getLng();
		$scope.center.lat = $scope.center.getLat();

		Page.ajaxPost('routeStat/stopsNearBy.do', {'lng' : $scope.center.lng, 'lat' : $scope.center.lat, 'radius' : 1000, 'num' : 20}, function(resp) {
			$scope.busStops = resp.data;

			$scope.showStops($scope.nearByNum);

		});
	}

	$scope.showStops = function (nearByNum) {

		// 删除历史marker，infoWindow，label
		$($scope.map.getAllOverlays('marker')).each(function (i , _marker) {
			if( _marker != $scope.startMarker && _marker != $scope.endMarker){
				$scope.map.remove(_marker);
			}
		})
		// $scope.map.remove($scope.displayedMarkers);
		$scope.map.clearInfoWindow();
		$scope.displayedMarkers = [];
		//

		//显示marker
		for(i = 0 ; i < nearByNum ; i++){
			var marker = new AMap.Marker({
				icon: 'img/icon/routeStat/mark_default.png',
				// content: '<div>1111</div>',
				position: [$scope.busStops[i].lng, $scope.busStops[i].lat],
				extData: {'stopId':$scope.busStops[i].stopId, 'stopName':$scope.busStops[i].stopName, 'stopLng':$scope.busStops[i].lng, 'stopLat':$scope.busStops[i].lat}
			});
			// marker.setAnimation('AMAP_ANIMATION_DROP');
			marker.setMap($scope.map);

			//设置标签
			/*marker.setLabel({
			 offset: new AMap.Pixel(8, 30),
			 content: $scope.busStops[i].stopName
			 });*/

			$scope.displayedMarkers.push(marker);
		}


		// 信息弹框
		$($scope.displayedMarkers).each(function (i, _marker) {

			_marker.on('click', function (e) {

				var html = '<div>' +
					'<div>'+
					'<div class="info" style="border: solid 1px silver;">'+
					'   <div class="info-top" style="position: relative;background: none repeat scroll 0 0 #5f94ea;border-bottom: 1px solid #CCC;border-radius: 5px 5px 0 0;">' +
					'       <div style="display: inline-block; color: #333333;font-size: 14px; font-weight: bold;line-height: 31px;padding: 0 10px;">' +  _marker.getExtData().stopName + '</div>' +
					'       <img style="position: absolute;top: 10px;right: 10px;transition-duration: 0.25s;" src="http://webapi.amap.com/images/close2.gif" ng-click="map.clearInfoWindow()">' +
					'   </div>' +
					'   <div class="info-middle" style="background-color: white; font-size: 12px;padding: 6px;line-height: 20px;">' +
					'       <button type="button" class="btn-defaul" ng-click="setStart()"><i class="fa fa-bus"> 设为起点</i></button>' +
					'       <button type="button" class="btn-defaul" ng-click="setEnd()"><i class="fa fa-bus"> 设为终点</i></button>' +
					'   </div>' +
					'   <div class="info-bottom" style="height: 0px;width: 100%;clear: both;text-align: center;">' +
					'       <img style="position: relative; z-index: 104;" src="http://webapi.amap.com/images/sharp.png">' +
					'   </div>'+
					'</div>' +
					'</div>' +
					'</div>';


				var template = angular.element(html);

				//编译模板
				var Element = $compile(template)($scope);

				infoWindow = new AMap.InfoWindow({
					isCustom: true,
					offset: new AMap.Pixel(15, -50),
					// content: html
					content: Element[0]
				});

				infoWindow.open($scope.map, e.target.getPosition());
				$scope.selectedMarker = _marker;
			});
		})
	};

	//注册地图拖动事件
	var clickEventListener = $scope.map.on('dragend', function(e) {
		$scope.center = $scope.map.getCenter();
		$scope.calcDistance($scope.center);
		$scope.showStops($scope.nearByNum);
		$scope.lastSearchName = '';
	});

	//注册地图缩放事件
	var clickEventListener = $scope.map.on('zoomend', function(e) {
		if( $scope.searchFlag == false) {
			$scope.center = $scope.map.getCenter();
			$scope.calcDistance($scope.center);
			$scope.showStops($scope.nearByNum);
			$scope.lastSearchName = '';
		}
	});

	//注册地图缩放事件
	var clickEventListener = $scope.map.on('moveend', function(e) {
		if( $scope.searchFlag == true){
			$scope.center = $scope.map.getCenter();
			$scope.calcDistance($scope.center);
			$scope.showStops($scope.nearByNum);
			$scope.searchFlag = false;
		}
	});

	//设为起点
	$scope.setStart = function() {
		//上次的marker恢复默认样式
		if( typeof $scope.startMarker == 'object') {
			$scope.startMarker.setIcon('img/icon/routeStat/mark_default.png');
			$scope.startMarker.setLabel({
				offset: new AMap.Pixel(8, 30),
				content: ''
			});
		}

		$scope.startMarker = $scope.selectedMarker;
		$scope.startMarker.setIcon('img/icon/routeStat/mark_start.png');
		$scope.startMarker.hide();
		$scope.startMarker.setAnimation('AMAP_ANIMATION_DROP');
		$scope.startMarker.setzIndex(200);
		$scope.startMarker.show();

		/*显示标签*/
		$scope.startMarker.setLabel({
			offset: new AMap.Pixel(8, 30),
			content: $scope.startMarker.getExtData().stopName
		});

		$($scope.displayedMarkers).each(function (i, _marker) {
			if( _marker != $scope.startMarker && _marker != $scope.endMarker){
				_marker.setIcon('img/icon/routeStat/mark_default.png');
			}
		});

		//起点-终点连接线
		if( typeof $scope.startMarker == 'object' && typeof $scope.endMarker == 'object') {
			$scope.map.remove($scope.selectedPolyline);
			var lineArr = [
				[$scope.startMarker.getPosition().lng, $scope.startMarker.getPosition().lat],
				[$scope.endMarker.getPosition().lng, $scope.endMarker.getPosition().lat]
			];
			$scope.selectedPolyline = new AMap.Polyline({
				path: lineArr,          //设置线覆盖物路径
				strokeColor: "#B4EEB4", //线颜色
				strokeOpacity: 0.9,       //线透明度
				strokeWeight: 6,        //线宽
				strokeStyle: "solid",   //线样式
				showDir: true,
				strokeDasharray: [10, 5] //补充线样式
			});
			$scope.selectedPolyline.setMap($scope.map);
		}

		$scope.map.clearInfoWindow();

		$scope.routeStat.startStopId = $scope.startMarker.getExtData().stopId ;
		$scope.routeStat.startStopName = $scope.startMarker.getExtData().stopName ;
		$scope.routeStat.startStopLng = $scope.startMarker.getExtData().stopLng ;
		$scope.routeStat.startStopLat = $scope.startMarker.getExtData().stopLat ;

	}

	//设为终点
	$scope.setEnd = function() {
		//上次的marker恢复默认样式
		if( typeof $scope.endMarker == 'object') {
			$scope.endMarker.setIcon('img/icon/routeStat/mark_default.png');
			$scope.endMarker.setLabel({
				offset: new AMap.Pixel(8, 30),
				content: ''
			});
		}

		$scope.endMarker = $scope.selectedMarker;
		$scope.endMarker.setIcon('img/icon/routeStat/mark_end.png');
		$scope.endMarker.hide();
		$scope.endMarker.setAnimation('AMAP_ANIMATION_DROP');
		$scope.endMarker.setzIndex(200);
		$scope.endMarker.show();

		/*显示标签*/
		$scope.endMarker.setLabel({
			offset: new AMap.Pixel(8, 30),
			content: $scope.endMarker.getExtData().stopName
		});

		$($scope.displayedMarkers).each(function (i, _marker) {
			if( _marker != $scope.startMarker && _marker != $scope.endMarker){
				_marker.setIcon('img/icon/routeStat/mark_default.png');
			}
		});

		//起点-终点连接线
		if( typeof $scope.startMarker == 'object' && typeof $scope.endMarker == 'object') {
			$scope.map.remove($scope.selectedPolyline);
			var lineArr = [
				[$scope.startMarker.getPosition().lng, $scope.startMarker.getPosition().lat],
				[$scope.endMarker.getPosition().lng, $scope.endMarker.getPosition().lat]
			];
			$scope.selectedPolyline = new AMap.Polyline({
				path: lineArr,          //设置线覆盖物路径
				strokeColor: "#B4EEB4", //线颜色
				strokeOpacity: 0.9,       //线透明度
				strokeWeight: 6,        //线宽
				strokeStyle: "solid",   //线样式
				showDir: true,
				strokeDasharray: [10, 5] //补充线样式
			});
			$scope.selectedPolyline.setMap($scope.map);
		}
		$scope.map.clearInfoWindow();

		$scope.routeStat.endStopId = $scope.endMarker.getExtData().stopId ;
		$scope.routeStat.endStopName = $scope.endMarker.getExtData().stopName ;
		$scope.routeStat.endStopLng = $scope.endMarker.getExtData().stopLng ;
		$scope.routeStat.endStopLat = $scope.endMarker.getExtData().stopLat ;

	}

	$scope.save = function () {

		// 数据验证
		if( typeof $scope.routeStat.startStopId == 'undefined'){
			$scope.alert = '请选择上车站点！';
			$scope.showAlert();
			return;
		}
		if( typeof $scope.routeStat.endStopId == 'undefined'){
			$scope.alert = '请选择下车站点！';
			$scope.showAlert();
			return;
		}
		if( typeof $scope.routeStat.departTime == 'undefined'){
			$scope.alert = '请选择出发时间！';
			$scope.showAlert();
			return;
		}

		$scope.routeStat.userId  = $rootScope.user.id;
		$scope.routeStat.departTime = $filter('date')($scope.routeStat.departTime, 'HH:mm');

		Page.ajaxPost('routeStat/add.do', $scope.routeStat, function(resp) {
			if(resp.data.resultCode > 0){
				$scope.alert = resp.data.resultMessage;
			}else{
				$scope.alert = resp.data.resultMessage;
			}
			$scope.showAlert();
		});
	}

	$scope.toggleSearchBar = function () {
		$scope.isSearchBar = !$scope.isSearchBar;
	}

	$scope.searchPlace = function () {
		if($scope.lastSearchName != $scope.searchName){
			$scope.searchFlag = true;
			$scope.placeSearch.search($scope.searchName);
			$scope.lastSearchName = $scope.searchName;
			$scope.searchName = '';
			$scope.isSearchBar = false;
		}
	}

	$scope.showAlert = function() {
		var alertPopup = $ionicPopup.show({
			cssClass:'alert',
			template: '<p id="pop-text">{{alert}}</p>',
			scope: $scope,
		});
		alertPopup.then(function(res) {
		});
		$timeout(function() {alertPopup.close();}, 1000);
	};

});